package com.ytjj.qmyx.data.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * xinyichen 短信发送工具类
 */
@Slf4j
public class SmsWayUtil {
    private static final String ACCOUNT="xxxxxx";
    private static final String PASSWORD="xxxxxxx";
//    private static final String SEND_URL="http://api.smsway.com.cn/api/send";
    private static final String SEND_URL="http://api.smsway.com.cn:8070/api/send/sendsms";
    private static final String EMAIL_SEND_URL="http://api.smsway.com.cn/api/compatible/emailAndSms";

    /**
     * 发信发送的目的号码.多个号码之间用半角逗号隔开,最多500个号码
     * @param mobile
     * @param content
     * @return
     */
    public static JSONObject sendSmsWithResult(String mobile,String content) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        List<NameValuePair> param = new ArrayList<>();
        param.add(new BasicNameValuePair("apiAccount",ACCOUNT));
        param.add(new BasicNameValuePair("secretKey",PASSWORD));
        param.add(new BasicNameValuePair("content",content));
        param.add(new BasicNameValuePair("mobiles",mobile));
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(SEND_URL);
            // 创建请求内容
            HttpEntity entity = new UrlEncodedFormEntity(param, "utf-8");
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JSON.parseObject(resultString);
    }

//    /**
//     * 发信发送的目的号码.多个号码之间用半角逗号隔开,最多500个号码 (原来的写法)
//     * @param mobile
//     * @param content
//     * @return
//     */
//    public static JSONObject sendSmsWithResult(String mobile,String content) {
//        StringBuilder sb = new StringBuilder();
//        sb.append("apiAccount="+ACCOUNT);
//        sb.append("&secretKey="+PASSWORD);
//        sb.append("&content="+content);
//        sb.append("&mobiles="+mobile);
//        String result=sendPostFormUrl(SEND_URL,sb.toString());
//        log.info("sendSmsWithResult,result={}",result);
//        return JSON.parseObject(result);
//    }

    public static String sendPostFormUrl(String url, String param) {
        log.info("sendData:" + param);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("Exception:" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        log.info("result:" + result);
        return result;

    }
/**
 * 设置二进制流实体，params 里面参数值为 file
 *
 * @param httpPost
 *            httpPsot 请求
 * @param params
 *             请求参数
 * @param file
 *            文件
 */
    private static void setMultipartEntityEntity(HttpPost httpPost, JSONObject params, File file) {
        String fileName = file==null?"":file.getName();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Iterator<String> keys = params.keySet().iterator();// 遍历 params 参数和值
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();// 新建builder对象
        while (keys.hasNext()) {
            String key = keys.next();
            String value = params.getString(key);
            if (value.equals("file")) {
                builder.addBinaryBody(key, inputStream, ContentType.create("multipart/form-data"), fileName);// 设置流参数
           } else {
               StringBody body = new StringBody(value, ContentType.create("text/plain", "utf-8"));// 设置普通参数
               builder.addPart(key, body);
           }
       }
        HttpEntity entity = builder.build();// 生成entity
        httpPost.setEntity(entity);// 设置 entity
    }
    public static void sendEmailAndSms(JSONObject params, File file) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpPost httppost = new HttpPost(EMAIL_SEND_URL);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);

            setMultipartEntityEntity(httppost,params,file);
            log.info("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                log.info(response.getStatusLine().toString());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseEntityStr = EntityUtils.toString(response.getEntity());
                    log.info(responseEntityStr);
                    log.info("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
//        JSONObject params=new JSONObject();
//        params.put("apiAccount",ACCOUNT);
//        params.put("secretKey",PASSWORD);
//        params.put("mobilesAndVariables","file");
//        params.put("templateId","3");
//
//        sendEmailAndSms(params,new File("D://email.zip"));
//        sendSmsWithResult("13786128343","测试");
    }
}
